package org.dromara.common.websocket.utils;

import java.util.UUID;
import java.util.UUID;

public class UUIDToByteArray {
    public static void main(String[] args) {
        // 输入的UUID字符串
        String uuidString = "a81edeb4e8c24f05896d61c680677083";

        // 将UUID字符串转换为byte数组
        byte[] uuidBytes = uuidToBytes(uuidString);

        // 打印结果
        System.out.println("UUID字符串: " + uuidString);
        System.out.println("转换后的byte数组长度: " + uuidBytes.length);
        System.out.print("byte数组内容: ");
        for (byte b : uuidBytes) {
            System.out.print(String.format("%02x ", b));
        }
    }


    /**
     * 为32位的UUID字符串添加横杠，转换为标准UUID格式
     *
     * @param uuid 32位无横杠的UUID字符串
     * @return 标准格式的UUID字符串
     */
    private static String formatUuid(String uuid) {
        return new StringBuilder(uuid)
            .insert(8, '-')
            .insert(13, '-')
            .insert(18, '-')
            .insert(23, '-')
            .toString();
    }

    /**
     * 将UUID字符串转换为byte数组
     *
     * @param uuidString UUID字符串
     * @return 对应的byte数组
     */
    public static byte[] uuidToBytes(String uuidString) {
        // 去除UUID中的所有横杠
        String processedUuid = uuidString.replaceAll("-", "");

        // 检查处理后的UUID长度是否正确
        if (processedUuid.length() != 32) {
            throw new IllegalArgumentException("无效的UUID字符串: " + uuidString);
        }

        // 为UUID添加横杠，以便正确解析
        String formattedUuid = formatUuid(processedUuid);

        // 解析UUID字符串
        UUID uuid = UUID.fromString(formattedUuid);

        // UUID由两个64位长整数组成，需要分别处理
        long mostSignificantBits = uuid.getMostSignificantBits();
        long leastSignificantBits = uuid.getLeastSignificantBits();

        // 创建16字节的数组存储UUID（128位）
        byte[] bytes = new byte[16];

        // 处理高64位
        for (int i = 0; i < 8; i++) {
            bytes[i] = (byte) (mostSignificantBits >>> 8 * (7 - i));
        }

        // 处理低64位
        for (int i = 8; i < 16; i++) {
            bytes[i] = (byte) (leastSignificantBits >>> 8 * (15 - i));
        }

        return bytes;
    }
}
